package com.lp.websocket;

import cn.hutool.extra.spring.SpringUtil;
import com.lp.service.GameService;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Created by sang on 2017/8/28.
 */
@ServerEndpoint("/game/{nickname}")
@Component
public class GoBangGame {
    private static final Set<GoBangGame> GO_BANG_GAME_SET = new CopyOnWriteArraySet<>();
    private Session session;
    private String nickname;
    private GameService gameService = SpringUtil.getBean(GameService.class);

    public static void sendText(String msg) {
        for (GoBangGame goBangGame : GO_BANG_GAME_SET) {
            try {
                synchronized (goBangGame) {
                    goBangGame.session.getBasicRemote().sendText(msg);
                }
            } catch (IOException e) {
                GO_BANG_GAME_SET.remove(goBangGame);
                try {
                    goBangGame.session.close();
                } catch (IOException e1) {
                }
                sendText(goBangGame.nickname + "童鞋已下线");
            }
        }
    }

    @OnOpen
    public void onOpen(@PathParam("nickname") String nickname, Session session) {
        this.session = session;
        this.nickname = nickname;
        GO_BANG_GAME_SET.add(this);
        gameService.addGame(nickname);
    }

    @OnMessage
    public void onMessage(String message, @PathParam("nickname") String nickname) {
        gameService.playGame(message, nickname);
    }

    @OnClose
    public void onClose(Session session) {
        GO_BANG_GAME_SET.remove(this);
        for (GoBangGame goBangGame : GO_BANG_GAME_SET) {
            if (goBangGame.nickname == this.nickname) {
                sendText(this.nickname + "童鞋已下线");
            }
        }
    }
}
